//
//  FWLoopView.swift
//  PicturesLooper
//
//  Created by 范伟 on 16/3/13.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import UIKit

private let ReuseID = "loopCell"

class FWLoopView: UICollectionView {

    private var imagePaths: [String]?
    private let didSelected: (index: Int) -> Void?
    

    init(imagePaths: [String], didSelected: (index: Int) -> Void) {
        self.imagePaths = imagePaths
        self.didSelected = didSelected
        super.init(frame: CGRectZero, collectionViewLayout: FWLoopViewLayout())
        backgroundColor = UIColor.whiteColor()
        dataSource = self
        delegate = self
        self.registerClass(FWLoopCell.self, forCellWithReuseIdentifier: ReuseID)
        // 判断图片数量，如果 > 1，将图片设置到数组的1倍的位置
        // 举个栗子：如果有3张图(0,1,2)，初始显示第 `3` 张图
        // 主队列异步，会在数据源方法执行之后，在执行 block 中的任务！
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            if imagePaths.count > 1 {
                let indexPath: NSIndexPath = NSIndexPath(forItem: imagePaths.count, inSection: 0)
                self.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
            }
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension FWLoopView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (imagePaths?.count ?? 1) * (imagePaths?.count == 1 ? 1 : 100)
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell: FWLoopCell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseID, forIndexPath: indexPath) as! FWLoopCell
        cell.imagePath = imagePaths?[indexPath.item % (imagePaths?.count ?? 1)]
        return cell
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        var page: Int = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        //判断是否是第一页或者是最后一页
        if page == 0 || page == numberOfItemsInSection(0) - 1 {
            page = (imagePaths?.count ?? 0) - (page == 0 ? 0 : 1)
            scrollView.contentOffset = CGPointMake(CGFloat(page) * scrollView.bounds.width, 0)
        }
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("\(indexPath.item % (imagePaths?.count ?? 1))")
        didSelected(index: indexPath.item % (imagePaths?.count ?? 1))
    }
}